'use strict';

const { wxapi } = require('use-api');

const {
	Controller
} = require('uni-cloud-router');
const dbcmd = uniCloud.database().command;

module.exports = class MessageController extends Controller {
	// 获取微信菜单
	async wxTemplateGet() {
		let response = {
			code: 1,
			datas: null,
			msg: ''
		};

		const wxTemplateUrl =
			'https://api.weixin.qq.com/cgi-bin/template/get_all_private_template';

		let start = Date.now();
		// 获取微信 access_token
		const token = await wxapi.get_token();

		const res = await this.curl(wxTemplateUrl, {
			nestedQuerystring: true,
			method: 'get',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			dataType: 'json',
			data: {
				access_token: token
			}
		});

		response.datas = res.data.template_list;

		let end = Date.now();
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}

	// 获取绑定二维码
	async wxQrcodeGet() {
		let response = {
			code: 1,
			datas: null,
			msg: ''
		};

		let {
			ids
		} = this.ctx.data;
		
		let start = Date.now();
		// 获取微信 access_token
		const token = await wxapi.get_token();

		const wxQrcodeUrl =
			`https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=${token}`;

		const res = await this.curl(wxQrcodeUrl, {
			nestedQuerystring: true,
			method: 'post',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			dataType: 'json',
			data: JSON.stringify({
				expire_seconds: 604800,
				action_name: 'QR_STR_SCENE',
				action_info: {
					scene: {
						scene_str: 'msg_' + ids[0]
					}
				}
			})
		});

		response.datas = {
			url: `https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=${res.data.ticket}`
		};

		let end = Date.now();
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}

	// 解绑
	async unbind() {
		let response = {
			code: 1,
			datas: null,
			msg: ''
		};

		let {
			row,
			item
		} = this.ctx.data;

		let start = Date.now();

		const res = await this.db.collection('wmzmall-message-type').doc(row._id).update({
			uids: dbcmd.pull(item.openid),
			users: dbcmd.pull({
				openid: item.openid
			})
		})
		
		response.datas = res;

		let end = Date.now();
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
}